package com.lhb.aicodemother.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.lhb.aicodemother.common.BaseResponse;
import com.lhb.aicodemother.common.ResultUtils;
import com.lhb.aicodemother.constant.AppConstant;
import com.lhb.aicodemother.exception.BusinessException;
import com.lhb.aicodemother.exception.ErrorCode;
import com.lhb.aicodemother.manager.CosManager;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;

/*
* 上传图片的接口
* */
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Resource
    private CosManager cosManager;

    private static final long IMAGE_SIZE = 1024 * 1024;

    /*
    * 上传图片返回路径
    * */
    @PostMapping("/image")
    public BaseResponse<String> uploadImage(MultipartFile file) {
        if(file.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"上传文件为空");
        }
        if(file.getSize() > IMAGE_SIZE){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片不能超过5M");
        }

        String dataPath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        int i = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
        String key = String.format("/%s/%s",dataPath,UUID.randomUUID().toString().substring(0, 8) + "." + file.getOriginalFilename().substring(i + 1));
        File sourceDir = new File(AppConstant.UPLOAD_FILE);
        if(!sourceDir.exists() || !sourceDir.isDirectory()){
            FileUtil.mkdir(sourceDir);
        }
        try{
            file.transferTo(new File(sourceDir,file.getOriginalFilename()));
        }catch (IOException e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String url = cosManager.uploadFile(key, new File(sourceDir,file.getOriginalFilename()));
        return ResultUtils.success(url);
    }
}
